
// 验证码不能点击切换的问题解决：设为全局函数
window.reloadCaptcha = function() {
    const captchaImage = document.getElementById("captcha-img");
    captchaImage.src = "/captcha?ts=" + Date.now();
};
document.addEventListener('DOMContentLoaded', () => {
    const forgetForm = document.getElementById('forgetForm');
    const getCaptchaBtn = document.getElementById('getCaptchaBtn');
    const errorMessage = document.getElementById('errorMessage');
    const emailInput = document.getElementById('user_mail');
    let countdown = 0;
    let countdownInterval;

    // 验证码图片刷新
    function reloadCaptcha() {
        document.getElementById("captcha-img").src = "/captcha?ts=" + Date.now();
    }

    // 邮箱验证
    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    // 显示错误信息
    function showError(msg) {
        errorMessage.textContent = msg;
        forgetForm.classList.add('shake');
        setTimeout(() => forgetForm.classList.remove('shake'), 500);
    }

    // 开始倒计时
    function startCountdown() {
        getCaptchaBtn.disabled = true;
        countdown = 60;

        getCaptchaBtn.textContent = `重新发送(${countdown}s)`;

        countdownInterval = setInterval(() => {
            countdown--;
            getCaptchaBtn.textContent = `重新发送(${countdown}s)`;

            if (countdown <= 0) {
                clearInterval(countdownInterval);
                getCaptchaBtn.disabled = false;
                getCaptchaBtn.textContent = '获取验证码';
            }
        }, 1000);
    }

    // 获取验证码按钮点击事件
    getCaptchaBtn.addEventListener('click', async () => {
        const email = emailInput.value.trim();

        if (!email) {
            showError('请输入邮箱地址');
            return;
        }

        if (!validateEmail(email)) {
            showError('请输入有效的邮箱地址');
            return;
        }
        // alert(email)
        try {
            // 发送获取验证码请求
            const response = await fetch('/send_captcha_to_email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ user_mail:email })

            });


            const result = await response.json();

            if (response.ok) {
                if (result.success) {
                    startCountdown();
                    showError('验证码已发送，请查收邮箱');
                } else {
                    showError(result.message || '发送验证码失败');
                }
            } else {
                showError(result.message || '服务器错误');
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            showError('网络错误，请稍后再试');
        }
    });

    // 表单提交事件
    forgetForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const email = emailInput.value.trim();
        const mailCaptcha = document.getElementById('mail_captcha').value.trim();
        const captcha = document.getElementById('captcha').value.trim();

        // 验证输入
        if (!email || !mailCaptcha || !captcha) {
            showError('请填写所有必填项');
            return;
        }

        try {
            // 发送验证请求
            const response = await fetch('/forget_password_process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    user_mail:email,
                    mail_captcha: mailCaptcha,
                    captcha:captcha
                })
            });

            const result = await response.json();

            if (response.ok) {
                if (result.success) {
                    // 跳转到重置密码页面
                    window.location.href = '/reset_password/' + result.token;
                } else {
                    showError(result.message || '验证失败');
                }
            } else {
                showError(result.message || '服务器错误');
            }
        } catch (error) {
            console.error('验证失败:', error);
            showError('网络错误，请稍后再试');
        }
    });

    // 获取Cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});